package com.menghao.sso.server.controller;

import com.menghao.sso.server.exception.ValidateFailException;
import com.menghao.sso.server.model.SimpleService;
import com.menghao.sso.server.service.AuthenticationService;
import com.menghao.sso.server.service.AuthorizationService;
import com.menghao.sso.server.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * <p>校验Controller.<br>
 *
 * @author menghao.
 * @version 2017/11/7.
 */
@Controller
@RequestMapping(CommonUtils.VALIDATE_URL)
public class ValidateController {

    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private AuthorizationService authorizationService;

    /**
     * 令牌校验（TGT or ST）
     *
     * @param request  (service、tgtId、stId)
     * @param response 用作重定向
     * @return ResponseEntity<String>
     */
    @GetMapping
    public ResponseEntity<Boolean> check(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateFailException {
        // Service
        String serviceUrl = URLDecoder.decode(request.getParameter(CommonUtils.SERVICE), "UTF-8");
        // TGT
        String tgtId = request.getParameter(CommonUtils.TGT_ID);
        // ST
        String stId = request.getParameter(CommonUtils.ST_ID);
        try {
            if (null != tgtId) {
                authenticationService.validateGrantingTicket(tgtId);
                String newStId = authorizationService.createServiceTicket(tgtId, new SimpleService(serviceUrl));
                StringBuilder builder = new StringBuilder(serviceUrl);
                if (serviceUrl.contains("?")) {
                    builder.append("&");
                } else {
                    builder.append("?");
                }
                builder.append(CommonUtils.ST_ID).append("=").append(newStId);
                response.sendRedirect(builder.toString());
            }
            if (null != stId) {
                authenticationService.validateServiceTicket(stId, new SimpleService(serviceUrl));
            }
        } catch (ValidateFailException e) {
            throw new ValidateFailException(serviceUrl, e.getMsg());
        }
        return new ResponseEntity<Boolean>(true, HttpStatus.OK);
    }
}
